#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试页面结构，找到正确的选择器
"""

from playwright.sync_api import sync_playwright
import logging

# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def debug_page_structure():
    """调试页面结构"""
    logger.info("🚀 开始调试页面结构...")
    
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context(
            user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            viewport={'width': 1920, 'height': 1080}
        )
        
        page = context.new_page()
        
        # 访问南宁烤肉页面
        url = "https://www.dianping.com/nanning/ch10/g34303"
        logger.info(f"🌐 访问页面: {url}")
        page.goto(url, timeout=30000)
        
        # 等待页面加载
        page.wait_for_load_state('networkidle', timeout=15000)
        logger.info("✅ 页面加载完成")
        
        # 等待用户手动操作
        input("请在浏览器中查看页面，然后按回车继续...")
        
        # 尝试不同的选择器
        selectors_to_try = [
            'li[class=""]',
            '.shop-list li',
            '.shop-item',
            '.shop-wrap',
            'li:has(.shop-name)',
            '.shop-list',
            '.list li',
            '.item',
            '.shop',
            'li',
            '.txt',
            '.tit',
            'h4',
            'a[title]',
            '.shopname',
            '.shop-name',
            '.title'
        ]
        
        logger.info("🔍 测试不同的选择器...")
        
        for selector in selectors_to_try:
            try:
                elements = page.query_selector_all(selector)
                if elements:
                    logger.info(f"✅ 选择器 '{selector}' 找到 {len(elements)} 个元素")
                    
                    # 显示前3个元素的文本内容
                    for i, element in enumerate(elements[:3]):
                        try:
                            text = element.inner_text()[:100]  # 只显示前100个字符
                            if text.strip():
                                logger.info(f"   元素{i+1}: {text.strip()}")
                        except:
                            pass
                else:
                    logger.info(f"❌ 选择器 '{selector}' 未找到元素")
            except Exception as e:
                logger.info(f"❌ 选择器 '{selector}' 出错: {e}")
        
        # 获取页面HTML结构（部分）
        logger.info("📄 获取页面HTML结构...")
        try:
            # 获取包含商铺信息的主要区域
            main_content = page.query_selector('body')
            if main_content:
                html_content = main_content.inner_html()
                
                # 查找包含店铺名称的部分
                import re
                shop_patterns = [
                    r'<h4[^>]*>([^<]+)</h4>',
                    r'title="([^"]*店[^"]*)"',
                    r'<a[^>]*title="([^"]*)"[^>]*>',
                    r'class="[^"]*shop[^"]*"[^>]*>([^<]+)<',
                    r'class="[^"]*tit[^"]*"[^>]*>([^<]+)<'
                ]
                
                for pattern in shop_patterns:
                    matches = re.findall(pattern, html_content, re.IGNORECASE)
                    if matches:
                        logger.info(f"🎯 模式 '{pattern}' 找到 {len(matches)} 个匹配:")
                        for i, match in enumerate(matches[:5]):
                            logger.info(f"   匹配{i+1}: {match.strip()}")
                        break
                        
        except Exception as e:
            logger.error(f"获取HTML结构失败: {e}")
        
        input("调试完成，按回车关闭浏览器...")

if __name__ == "__main__":
    debug_page_structure()
